// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.StockIn;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryExchangeVo;
import com.fowo.api.inventory.model.InventoryStorageVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.model.form.InventoryStorageFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.StockInMapper;
import com.fowo.api.mapper.StockInProductMapper;
import com.fowo.api.model.stock.in.StockInApplyInBatchStorageAction;
import com.fowo.api.model.stock.in.StockInConfirmWarehouseAction;
import com.fowo.api.model.stock.in.StockInCustomUpdateStockInStatusVo;
import com.fowo.api.model.stock.in.StockInExcelPo;
import com.fowo.api.model.stock.in.StockInItemVo;
import com.fowo.api.model.stock.in.StockInPushLingXingAction;
import com.fowo.api.model.stock.in.StockInPushPayableAction;
import com.fowo.api.model.stock.in.StockInPushSellOrderAction;
import com.fowo.api.model.stock.in.StockInPushStockOtherAction;
import com.fowo.api.model.stock.in.StockInPushprocessAction;
import com.fowo.api.model.stock.in.StockInResubmitAction;
import com.fowo.api.model.stock.in.StockInRevokeWarehousingAction;
import com.fowo.api.model.stock.in.StockInSearchParamPo;
import com.fowo.api.model.stock.in.StockInSyncWarehousingOrderAction;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.constant.StockInCategoryIdEnums;
import com.fowo.api.model.stock.in.constant.StockInCostAllocationTypeEnums;
import com.fowo.api.model.stock.in.constant.StockInGenerateApEnums;
import com.fowo.api.model.stock.in.constant.StockInProductTypeEnums;
import com.fowo.api.model.stock.in.constant.StockInRevocationEnums;
import com.fowo.api.model.stock.in.constant.StockInStatusEnums;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVoPages;
import com.fowo.api.model.stock.in.product.StockInProductSearchParamPo;
import com.fowo.api.service.StockInProductService;
import com.fowo.api.service.StockInService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.AccessManager;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.FieldPermissionGroupManager;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入库单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，王阳阳
 */
@Slf4j
@DataObjectType(StockIn.class)
@DS("ds24")
public class StockInBaseServiceImpl
  extends ServiceImpl<StockInMapper, StockIn>
  implements StockInService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("warehouseName", "w.`name`");
      put("supplierSupplierName", "s.`supplier_name`");
      put("createUserName", "su.`name`");
      put("applicationDepName", "sd.`name`");
      put("cgUidName", "su2.`name`");
      put("purchasingOrgName", "do.`name`");
      put("needOrgName", "do2.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected StockInService self;

  @Resource
  protected StockInProductService stockInProductService;

  @Resource
  protected FieldPermissionGroupManager fieldPermissionGroupManager;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected AccessManager accessManager;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected StockInPushLingXingAction stockInPushLingXingAction;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected StockInConfirmWarehouseAction stockInConfirmWarehouseAction;

  @Autowired(required = false)
  protected StockInResubmitAction stockInResubmitAction;

  @Autowired(required = false)
  protected StockInRevokeWarehousingAction stockInRevokeWarehousingAction;

  @Autowired(required = false)
  protected StockInPushprocessAction stockInPushprocessAction;

  @Autowired(required = false)
  protected StockInApplyInBatchStorageAction stockInApplyInBatchStorageAction;

  @Autowired(required = false)
  protected StockInPushStockOtherAction stockInPushStockOtherAction;

  @Autowired(required = false)
  protected StockInPushSellOrderAction stockInPushSellOrderAction;

  @Autowired(required = false)
  protected StockInPushPayableAction stockInPushPayableAction;

  @Autowired(required = false)
  protected StockInSyncWarehousingOrderAction stockInSyncWarehousingOrderAction;

  @Resource
  protected Validator validator;

  /**
   * 创建入库单
   * @param model 入库单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(StockInVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    // 字段权限组过滤
    fieldPermissionGroupManager.filterFields(
      model,
      "stockPrice",
      "accessoriesTotalAmount",
      "totalAmount"
    );
    StockIn entity = new StockIn();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getReceiptType() == null) {
      entity.setReceiptType("RK002");
    }

    if (model.getCostAllocationType() == null) {
      entity.setCostAllocationType("1");
    }

    if (model.getRevocation() == null) {
      entity.setRevocation("0");
    }

    if (model.getAStatus() == null) {
      entity.setAStatus("committed");
    }

    if (model.getStatus() == null) {
      entity.setStatus("2");
    }

    if (model.getIsPush() == null) {
      entity.setIsPush(false);
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderSn())) {
      entity.setOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "StockIn.orderSn")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("入库单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 入库单
   */
  protected void updateAllChilds(StockInVo model) throws Exception {
    if (model.getProductList() != null) {
      stockInProductService.saveAllByParentStockInId(
        model.getId(),
        model.getProductList()
      );
    }
  }

  /**
   * 更新入库单
   * @param model 入库单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(StockInVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockIn entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("入库单不存在");
    }
    // 字段权限组过滤
    fieldPermissionGroupManager.filterFields(
      model,
      "stockPrice",
      "accessoriesTotalAmount",
      "totalAmount"
    );
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createUser",
      "createTime",
      "accessoriesTotalAmount",
      "totalAmount",
      "totalNum",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新入库单（带空值）
   * @param model 入库单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(StockInVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockIn entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("入库单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    // 需要 stockPrice 权限才能更新 accessoriesTotalAmount,totalAmount
    boolean authorityStockPrice = accessManager.canAccess("stockPrice");
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(StockIn::getWarehouse, model.getWarehouse())
      .set(StockIn::getReceiptType, model.getReceiptType())
      .set(StockIn::getSupplier, model.getSupplier())
      .set(StockIn::getRemarks, model.getRemarks())
      .set(StockIn::getFreight, model.getFreight())
      .set(StockIn::getOtherExpenses, model.getOtherExpenses())
      .set(StockIn::getCostAllocationType, model.getCostAllocationType())
      .set(StockIn::getWarehousingDate, model.getWarehousingDate())
      .set(
        model.getEnclosure() != null,
        StockIn::getEnclosure,
        JSON.toJSONString(model.getEnclosure())
      )
      .setSql(model.getEnclosure() == null, "enclosure = null")
      .set(StockIn::getApplicationDep, model.getApplicationDep())
      .set(StockIn::getProductType, model.getProductType())
      .set(StockIn::getLastUpdateTime, model.getLastUpdateTime())
      .set(StockIn::getLastUpdateUser, model.getLastUpdateUser())
      .set(StockIn::getPurchasingOrg, model.getPurchasingOrg())
      .set(StockIn::getNeedOrg, model.getNeedOrg())
      .set(StockIn::getRejectRemark, model.getRejectRemark())
      .set(StockIn::getCategoryId, model.getCategoryId())
      .eq(StockIn::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(StockInSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 商品列表(productList) 对应的对象
    StockInProductSearchParamPo productListSearchParam =
      new StockInProductSearchParamPo();
    productListSearchParam.setDisableDataPremissions(true);
    productListSearchParam.setParentStockInIdInList(ids);
    StockInProductMapper localStockInProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(StockInProductMapper.class);
    productListSearchParam.applySqlSegments();
    List<Long> productListIdList = localStockInProductMapper.searchIds(
      productListSearchParam
    );
    if (!productListIdList.isEmpty()) {
      StockInProductService localStockInProductService = ContextHolder
        .getApplicationContext()
        .getBean(StockInProductService.class);
      localStockInProductService.batchDelete(productListIdList);
    }
  }

  /**
   * 删除入库单
   * @param id 入库单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除入库单
   * @param ids 入库单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    StockInSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.setChildMappingOption(
        new CustomExcelExport.ChildMappingOption()
          .setFieldName("productList")
          .setChildPageSearch((parentRecord, current, pageSize) -> {
            StockInItemVo parent = (StockInItemVo) parentRecord;
            StockInProductSearchParamPo searchParamPo =
              new StockInProductSearchParamPo();
            searchParamPo.setCurrent(current);
            searchParamPo.setPageSize(pageSize);
            searchParamPo.setParentStockInIdEq(parent.getId());
            return stockInProductService.pageSearch(searchParamPo);
          })
      );
      exportOptions.addFieldMappingOption(
        "productList.productId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInProductItemVo) r).getProductIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productList.fnsku",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInProductItemVo) r).getFnskuFnsku())
          )
      );
      exportOptions.addFieldMappingOption(
        "productList.shopId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInProductItemVo) r).getShopIdShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productList.positions",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInProductItemVo) r).getPositionsStorageBin())
          )
      );
      exportOptions.addFieldMappingOption(
        "productList.defectiveProductPosition",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((StockInProductItemVo) r).getDefectiveProductPositionStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productList.parentStockInId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((StockInProductItemVo) r).getParentStockInIdCgRealname()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productList.warehouseId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInProductItemVo) r).getWarehouseIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInItemVo) r).getWarehouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "receiptType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00001")
      );
      exportOptions.addFieldMappingOption(
        "supplier",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInItemVo) r).getSupplierSupplierName())
          )
      );
      exportOptions.addFieldMappingOption(
        "costAllocationType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            StockInCostAllocationTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "warehousingDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "applicationDep",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInItemVo) r).getApplicationDepName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> StockInProductTypeEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "generateAp",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> StockInGenerateApEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "revocation",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> StockInRevocationEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "cgUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInItemVo) r).getCgUidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "purchasingOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInItemVo) r).getPurchasingOrgName())
          )
      );
      exportOptions.addFieldMappingOption(
        "needOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockInItemVo) r).getNeedOrgName())
          )
      );
      exportOptions.addFieldMappingOption(
        "addType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00035")
      );
      exportOptions.addFieldMappingOption(
        "aStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00081")
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> StockInStatusEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "categoryId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> StockInCategoryIdEnums.toLabel((String) o))
      );
      exportOptions.addStringFields(
        "formId.productIdName",
        "formId.sku",
        "formId.fnskuFnsku",
        "formId.shopIdShopName",
        "formId.positionsStorageBin",
        "formId.productTag",
        "formId.defectiveProductPositionStorageBin",
        "formId.remarks",
        "formId.parentStockInIdCgRealname",
        "formId.warehouseIdName",
        "formId.productName",
        "formId.shopName",
        "formId.handle",
        "formId.warehouseName",
        "formId.ingredients",
        "formId.lxFnsku",
        "orderSn",
        "warehouseName",
        "receiptType",
        "supplierSupplierName",
        "associatedPo",
        "totalStorage",
        "remarks",
        "purchaseOrderCode",
        "costAllocationType",
        "accessoriesTotalAmount",
        "totalAmount",
        "totalNum",
        "applicationDepName",
        "productType",
        "cgRealname",
        "generateAp",
        "revocation",
        "applicationDepName1",
        "wid",
        "cgUidName",
        "purchasingOrgName",
        "needOrgName",
        "addType",
        "aStatus",
        "status",
        "parentId",
        "isPush",
        "rejectRemark",
        "categoryId"
      );

      String fileName = String.format(
        "入库单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> receiptTypeItems = sysDictService.getDictItems(
      "SCM00001"
    );
    List<SysDictAllItem> addTypeItems = sysDictService.getDictItems("SCM00035");
    List<SysDictAllItem> aStatusItems = sysDictService.getDictItems("SCM00081");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<StockInExcelPo> items = new ArrayList<StockInExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<StockInItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<StockInItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (StockInItemVo item : list) {
        StockInExcelPo excel = new StockInExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getReceiptType() != null) {
          receiptTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getReceiptType()))
            .findFirst()
            .ifPresent(i -> excel.setReceiptType(i.getItemText()));
        }
        excel.setCostAllocationType(
          StockInCostAllocationTypeEnums.toLabel(item.getCostAllocationType())
        );
        excel.setProductType(
          StockInProductTypeEnums.toLabel(item.getProductType())
        );
        excel.setGenerateAp(
          StockInGenerateApEnums.toLabel(item.getGenerateAp())
        );
        excel.setRevocation(
          StockInRevocationEnums.toLabel(item.getRevocation())
        );
        if (item.getAddType() != null) {
          addTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getAddType()))
            .findFirst()
            .ifPresent(i -> excel.setAddType(i.getItemText()));
        }
        if (item.getAStatus() != null) {
          aStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getAStatus()))
            .findFirst()
            .ifPresent(i -> excel.setAStatus(i.getItemText()));
        }
        excel.setStatus(StockInStatusEnums.toLabel(item.getStatus()));
        if (item.getIsPush() != null) {
          excel.setIsPush(item.getIsPush() ? "是" : "否");
        }
        excel.setCategoryId(
          StockInCategoryIdEnums.toLabel(item.getCategoryId())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "入库单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(StockInExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过采购员查询入库单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByCgRealname(String cgRealname) {
    return this.baseMapper.getIdByCgRealname(cgRealname);
  }

  /**
   * 通过采购员查询入库单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByCgRealname(List<String> list) {
    return this.baseMapper.getIdsByCgRealname(list);
  }

  /**
   * 通过入库单主键查询采购员
   */
  @Override
  public String getCgRealnameById(Long id) {
    return this.baseMapper.getCgRealnameById(id);
  }

  /**
   * 通过入库单主键查询采购员列表
   */
  @Override
  public List<String> getCgRealnameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getCgRealnameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("cgRealname"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 入库单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public StockInVo getVoById(Long id) throws Exception {
    StockInVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    StockInProductSearchParamPo productListSearchParamPo =
      new StockInProductSearchParamPo();
    productListSearchParamPo.setParentStockInId(id);
    productListSearchParamPo.getExtendData().put("queryMode", "sub");
    productListSearchParamPo.getExtendData().put("queryParent", "StockIn");
    productListSearchParamPo.applySqlSegments();
    vo.setProductList(stockInProductService.search(productListSearchParamPo));

    // 字段权限组过滤
    fieldPermissionGroupManager.filterFields(
      vo,
      "stockPrice",
      "accessoriesTotalAmount",
      "totalAmount"
    );
    return vo;
  }

  /**
   * 分页查询入库单
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<StockInItemVo> pageSearch(StockInSearchParamPo search) {
    Page<StockInItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    // 字段权限组过滤
    fieldPermissionGroupManager.filterItemFields(
      page.getRecords(),
      "stockPrice",
      "accessoriesTotalAmount",
      "totalAmount"
    );
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(StockInItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<StockInItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<StockInItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    StockInProductSearchParamPo productListSearchParamPo =
      new StockInProductSearchParamPo();
    productListSearchParamPo.setSort(sort);
    productListSearchParamPo.setPageSize(200);
    productListSearchParamPo.setParentStockInIdInList(
      pageResult
        .getRecords()
        .stream()
        .map(StockInItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<StockInProductItemVoPages>> productListMaps =
      stockInProductService.pagesByParentStockInId(productListSearchParamPo);

    for (StockInItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "productList",
        productListMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(StockInSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    StockInSearchParamPo search
  ) {
    StockInSearchParamPo parentSearchParam = new StockInSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<StockInItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      StockInItemVo itemVo = parentList.get(0);

      StockInProductSearchParamPo productListSearchParamPo =
        new StockInProductSearchParamPo();
      productListSearchParamPo.setPageSize(search.getPageSize());
      productListSearchParamPo.setCurrent(search.getCurrent());
      productListSearchParamPo.setParentStockInId(itemVo.getId());
      return stockInProductService.pageSearch(productListSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 入库单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'StockInOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<StockInItemVo>> searchOptions(
    StockInSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询入库单
   * @param search 查询条件
   * @return 入库单列表查询结果
   */
  @Override
  public List<StockInItemVo> search(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询入库单最后更新时间
   * @param search 查询条件
   * @return 入库单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(StockInSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 返回满足搜索条件的统计信息
   * @param search 搜索参数
   */
  @Override
  public Map<String, Object> searchForStatistical(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchForStatistical(search);
  }

  /**
   * 推送领星
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了推送领星操作"
  )
  @Override
  public void pushLingXing(Long id) throws Exception {
    if (stockInPushLingXingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInPushLingXingAction.run(id);
  }

  /**
   * 撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void custCancelAudit(Long id) throws Exception {
    StockInVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareCustCancelAudit(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    StockIn updateStatusEntity = new StockIn();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("3");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 撤销 的参数
   */
  protected InventoryStorageFormVo prepareCustCancelAudit(StockInVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("撤销入库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    if (vo.getRemarks() != null) {
      formVo.setUserData8(vo.getRemarks().toString());
    }
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getQuantity())
      );
      storageItem.setShopId(
        String.valueOf(stockInProduct.getShopId()).equals("null")
          ? null
          : String.valueOf(stockInProduct.getShopId())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            stockInProduct.getLxFnsku() == null
              ? null
              : stockInProduct.getLxFnsku().trim()
          )
          ? null
          : String.valueOf(stockInProduct.getLxFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockInProduct.getPositions(),
        Integer.parseInt(
          String.valueOf(stockInProduct.getQuantity()).equals("null")
            ? "0"
            : String.valueOf(stockInProduct.getQuantity())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void refer(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockIn_refer.js",
      id,
      null,
      this
    );
  }

  /**
   * 确认入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认入库操作"
  )
  @Override
  public void confirmWarehouse(Long id) throws Exception {
    if (stockInConfirmWarehouseAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInConfirmWarehouseAction.run(id);
  }

  /**
   * 重新提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了重新提交操作"
  )
  @Override
  public void resubmit(List<Long> ids) throws Exception {
    if (stockInResubmitAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInResubmitAction.run(ids);
  }

  /**
   * 批量撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量撤销操作"
  )
  @Override
  public void revokeWarehousing(List<Long> ids) throws Exception {
    if (stockInRevokeWarehousingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInRevokeWarehousingAction.run(ids);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void custSubmitOrder(List<Long> ids) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockIn_custSubmitOrder.js",
      ids,
      null,
      this
    );
  }

  /**
   * 生成加工单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了生成加工单操作"
  )
  @Override
  public void pushprocess(List<Long> ids) throws Exception {
    if (stockInPushprocessAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInPushprocessAction.run(ids);
  }

  /**
   * 批量审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量审核操作"
  )
  @Override
  public void applyInBatchStorage(List<Long> ids) throws Exception {
    if (stockInApplyInBatchStorageAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInApplyInBatchStorageAction.run(ids);
  }

  /**
   * 入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了入库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void ruku(Long id) throws Exception {
    StockInVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareRuku(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    StockIn updateStatusEntity = new StockIn();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 入库 的参数
   */
  protected InventoryStorageFormVo prepareRuku(StockInVo vo) throws Exception {
    if (!"0".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("采购入库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    if (vo.getRemarks() != null) {
      formVo.setUserData8(vo.getRemarks().toString());
    }
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getQuantity())
      );
      storageItem.setShopId(
        String.valueOf(stockInProduct.getShopId()).equals("null")
          ? null
          : String.valueOf(stockInProduct.getShopId())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            stockInProduct.getLxFnsku() == null
              ? null
              : stockInProduct.getLxFnsku().trim()
          )
          ? null
          : String.valueOf(stockInProduct.getLxFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockInProduct.getPositions(),
        Integer.parseInt(
          String.valueOf(stockInProduct.getQuantity()).equals("null")
            ? "0"
            : String.valueOf(stockInProduct.getQuantity())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 下推其他出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推其他出库单操作"
  )
  @Override
  public void pushStockOther(Long id) throws Exception {
    if (stockInPushStockOtherAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInPushStockOtherAction.run(id);
  }

  /**
   * 库存流转
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了库存流转操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void inventoryTurnover(Long id) throws Exception {
    StockInVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareInventoryTurnover(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    StockIn updateStatusEntity = new StockIn();
    updateStatusEntity.setId(id);
    updateStatusEntity.setAStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 库存流转 的参数
   */
  protected InventoryExchangeFormVo prepareInventoryTurnover(StockInVo vo)
    throws Exception {
    if (!"0".equals(vo.getAStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(StockInVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getId().toString());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWarehouse());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    if (vo.getRemarks() != null) {
      formVo.setUserData8(vo.getRemarks().toString());
    }
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(stockInProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(stockInProduct.getShopId()).equals("null")
          ? null
          : String.valueOf(stockInProduct.getShopId())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            stockInProduct.getLxFnsku() == null
              ? null
              : stockInProduct.getLxFnsku().trim()
          )
          ? null
          : String.valueOf(stockInProduct.getLxFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockInProduct.getPositions(),
        Integer.parseInt(
          String.valueOf(stockInProduct.getUnitStock()).equals("null")
            ? "0"
            : String.valueOf(stockInProduct.getUnitStock())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        stockInProduct.getPositions(),
        Integer.parseInt(
          String.valueOf(stockInProduct.getQuantity()).equals("null")
            ? "0"
            : String.valueOf(stockInProduct.getQuantity())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(stockInProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 入库次品
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了入库次品操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void rukucipin(Long id) throws Exception {
    StockInVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareRukucipin(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    StockIn updateStatusEntity = new StockIn();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 入库次品 的参数
   */
  protected InventoryStorageFormVo prepareRukucipin(StockInVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setTo(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("采购入库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    if (vo.getRemarks() != null) {
      formVo.setUserData8(vo.getRemarks().toString());
    }
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getDefectiveProduct()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getDefectiveProduct())
      );
      storageItem.setShopId(
        String.valueOf(stockInProduct.getShopId()).equals("null")
          ? null
          : String.valueOf(stockInProduct.getShopId())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            stockInProduct.getLxFnsku() == null
              ? null
              : stockInProduct.getLxFnsku().trim()
          )
          ? null
          : String.valueOf(stockInProduct.getLxFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockInProduct.getDefectiveProductPosition(),
        Integer.parseInt(
          String.valueOf(stockInProduct.getDefectiveProduct()).equals("null")
            ? "0"
            : String.valueOf(stockInProduct.getDefectiveProduct())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 下推销售出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推销售出库单操作"
  )
  @Override
  public void pushSellOrder(Long id) throws Exception {
    if (stockInPushSellOrderAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInPushSellOrderAction.run(id);
  }

  /**
   * 入库待检量
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了入库待检量操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void ruku3(Long id) throws Exception {
    StockInVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareRuku3(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    StockIn updateStatusEntity = new StockIn();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 入库待检量 的参数
   */
  protected InventoryStorageFormVo prepareRuku3(StockInVo vo) throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setTo(TargetTypeEnum.Inspected);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("采购入库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    if (vo.getRemarks() != null) {
      formVo.setUserData8(vo.getRemarks().toString());
    }
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getWaitQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getWaitQuantity())
      );
      storageItem.setShopId(
        String.valueOf(stockInProduct.getShopId()).equals("null")
          ? null
          : String.valueOf(stockInProduct.getShopId())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            stockInProduct.getLxFnsku() == null
              ? null
              : stockInProduct.getLxFnsku().trim()
          )
          ? null
          : String.valueOf(stockInProduct.getLxFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockInProduct.getPositions(),
        Integer.parseInt(
          String.valueOf(stockInProduct.getWaitQuantity()).equals("null")
            ? "0"
            : String.valueOf(stockInProduct.getWaitQuantity())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelWarehousing(Long id) throws Exception {
    StockInVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareCancelWarehousing(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    StockIn updateStatusEntity = new StockIn();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("3");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 撤销 的参数
   */
  protected InventoryStorageFormVo prepareCancelWarehousing(StockInVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    if (vo.getRemarks() != null) {
      formVo.setUserData8(vo.getRemarks().toString());
    }
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getQuantity())
      );
      storageItem.setShopId(
        String.valueOf(stockInProduct.getShopId()).equals("null")
          ? null
          : String.valueOf(stockInProduct.getShopId())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            stockInProduct.getLxFnsku() == null
              ? null
              : stockInProduct.getLxFnsku().trim()
          )
          ? null
          : String.valueOf(stockInProduct.getLxFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockInProduct.getPositions(),
        Integer.parseInt(
          String.valueOf(stockInProduct.getQuantity()).equals("null")
            ? "0"
            : String.valueOf(stockInProduct.getQuantity())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 下推应付单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推应付单操作"
  )
  @Override
  public void pushPayable(Long id) throws Exception {
    if (stockInPushPayableAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInPushPayableAction.run(id);
  }

  /**
   * 同步领星入库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步领星入库单操作"
  )
  @Override
  public void syncWarehousingOrder() throws Exception {
    if (stockInSyncWarehousingOrderAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInSyncWarehousingOrderAction.run();
  }

  /**
   * 提交表单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交表单操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void custSmtStockin(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockIn_custSmtStockin.js",
      id,
      null,
      this
    );
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    StockInSearchParamPo search = new StockInSearchParamPo();
    return MapUtil
      .builder()
      .put("Entire", this.baseMapper.entireCount(search))
      .put(
        "ChangesToBeCommitted",
        this.baseMapper.changesToBeCommittedCount(search)
      )
      .put("StockPending", this.baseMapper.stockPendingCount(search))
      .put("Completed", this.baseMapper.completedCount(search))
      .put("Undone", this.baseMapper.undoneCount(search))
      .put("Reject", this.baseMapper.rejectCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<StockInItemVo> entire(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.entire(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<StockInItemVo> entirePage(StockInSearchParamPo search) {
    Page<StockInItemVo> entirePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return entirePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return entirePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    entirePage =
      this.baseMapper.entirePage(
          search.toPage(this.baseMapper.entireCount(search)),
          search
        );
    List<Long> recordIds = entirePage
      .getRecords()
      .stream()
      .map(StockInItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return entirePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return entirePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    entirePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return entirePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<?> entirePageWithChildSearch(StockInSearchParamPo search) {
    return appendWithChild(
      entirePage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date entireLastUpdateTime(StockInSearchParamPo search) {
    return this.baseMapper.entireLastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<StockInItemVo> changesToBeCommitted(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.changesToBeCommitted(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<StockInItemVo> changesToBeCommittedPage(
    StockInSearchParamPo search
  ) {
    Page<StockInItemVo> changesToBeCommittedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return changesToBeCommittedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return changesToBeCommittedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    changesToBeCommittedPage =
      this.baseMapper.changesToBeCommittedPage(
          search.toPage(this.baseMapper.changesToBeCommittedCount(search)),
          search
        );
    List<Long> recordIds = changesToBeCommittedPage
      .getRecords()
      .stream()
      .map(StockInItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return changesToBeCommittedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return changesToBeCommittedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    changesToBeCommittedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return changesToBeCommittedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<?> changesToBeCommittedPageWithChildSearch(
    StockInSearchParamPo search
  ) {
    return appendWithChild(
      changesToBeCommittedPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date changesToBeCommittedLastUpdateTime(StockInSearchParamPo search) {
    return this.baseMapper.changesToBeCommittedLastUpdateTime(search);
  }

  /**
   * 待入库
   */
  @Override
  public List<StockInItemVo> stockPending(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.stockPending(search);
  }

  /**
   * 待入库分页
   */
  @Override
  public Page<StockInItemVo> stockPendingPage(StockInSearchParamPo search) {
    Page<StockInItemVo> stockPendingPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return stockPendingPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return stockPendingPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    stockPendingPage =
      this.baseMapper.stockPendingPage(
          search.toPage(this.baseMapper.stockPendingCount(search)),
          search
        );
    List<Long> recordIds = stockPendingPage
      .getRecords()
      .stream()
      .map(StockInItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return stockPendingPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return stockPendingPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    stockPendingPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return stockPendingPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<?> stockPendingPageWithChildSearch(StockInSearchParamPo search) {
    return appendWithChild(
      stockPendingPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询待入库最后更新时间
   * @param search 查询条件
   * @return 待入库最后更新时间
   */
  @Override
  public Date stockPendingLastUpdateTime(StockInSearchParamPo search) {
    return this.baseMapper.stockPendingLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<StockInItemVo> completed(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.completed(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<StockInItemVo> completedPage(StockInSearchParamPo search) {
    Page<StockInItemVo> completedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return completedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return completedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    completedPage =
      this.baseMapper.completedPage(
          search.toPage(this.baseMapper.completedCount(search)),
          search
        );
    List<Long> recordIds = completedPage
      .getRecords()
      .stream()
      .map(StockInItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return completedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return completedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    completedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return completedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<?> completedPageWithChildSearch(StockInSearchParamPo search) {
    return appendWithChild(
      completedPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date completedLastUpdateTime(StockInSearchParamPo search) {
    return this.baseMapper.completedLastUpdateTime(search);
  }

  /**
   * 已撤销
   */
  @Override
  public List<StockInItemVo> undone(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.undone(search);
  }

  /**
   * 已撤销分页
   */
  @Override
  public Page<StockInItemVo> undonePage(StockInSearchParamPo search) {
    Page<StockInItemVo> undonePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return undonePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return undonePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    undonePage =
      this.baseMapper.undonePage(
          search.toPage(this.baseMapper.undoneCount(search)),
          search
        );
    List<Long> recordIds = undonePage
      .getRecords()
      .stream()
      .map(StockInItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return undonePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return undonePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    undonePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return undonePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<?> undonePageWithChildSearch(StockInSearchParamPo search) {
    return appendWithChild(
      undonePage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询已撤销最后更新时间
   * @param search 查询条件
   * @return 已撤销最后更新时间
   */
  @Override
  public Date undoneLastUpdateTime(StockInSearchParamPo search) {
    return this.baseMapper.undoneLastUpdateTime(search);
  }

  /**
   * 已驳回
   */
  @Override
  public List<StockInItemVo> reject(StockInSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.reject(search);
  }

  /**
   * 已驳回分页
   */
  @Override
  public Page<StockInItemVo> rejectPage(StockInSearchParamPo search) {
    Page<StockInItemVo> rejectPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return rejectPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return rejectPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    rejectPage =
      this.baseMapper.rejectPage(
          search.toPage(this.baseMapper.rejectCount(search)),
          search
        );
    List<Long> recordIds = rejectPage
      .getRecords()
      .stream()
      .map(StockInItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return rejectPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return rejectPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    rejectPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return rejectPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 入库单分页查询结果
   */
  @Override
  public Page<?> rejectPageWithChildSearch(StockInSearchParamPo search) {
    return appendWithChild(
      rejectPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询已驳回最后更新时间
   * @param search 查询条件
   * @return 已驳回最后更新时间
   */
  @Override
  public Date rejectLastUpdateTime(StockInSearchParamPo search) {
    return this.baseMapper.rejectLastUpdateTime(search);
  }

  /**
   * 更新入库单单据状态
   */
  @Override
  @DataActivity(action = SysDataActivityAction.Modified)
  @Transactional(rollbackFor = Exception.class)
  public boolean customUpdateStockInStatus(
    StockInCustomUpdateStockInStatusVo customUpdateStockInStatusVo
  ) throws Exception {
    StockInVo updateStockIn = new StockInVo();
    BeanUtils.copyProperties(customUpdateStockInStatusVo, updateStockIn);
    return update(updateStockIn);
  }
}
